<?php

class Suning
{
    public $app_key = '';
    public $app_secret='';
    public $data=[];


    public $status      = [
        '等待付款'  => 1,
        '支付完成'  => 2,
        '退款'    => 11,
        '订单已取消' => 11,
        '确认收货'  => 6,
    ];

    public function __construct($union)
    {
        $this->app_key = $union['appKey'];
        $this->app_secret = $union['appSecret'];
        require_once "suning/SuningSdk.php";
        require_once "suning/DefaultSuningClient.php";
    }

    function getReqJson($req){
        $paramsArray = $req -> getApiParams();
        if(empty($paramsArray)){
            $paramsArray = '';
        }
        $paramsArray = array('sn_request' => array('sn_body' => array(
            "{$req -> getBizName()}" => $paramsArray
        )));
        return json_encode($paramsArray);
    }



    /**
     * @param $data 数据转换
     */
    public function trans_list_data($data)
    {
        $new_data = [];
        foreach ($data as $key => $value) {
            $new_data[$key]["GoodsId"]       = $value['commodityInfo']['commodityCode'].'-'.$value['commodityInfo']['supplierCode'];
            $new_data[$key]["Title"]         = $value["commodityInfo"]['commodityName'];
            $new_data[$key]["ShortTitle"]    = $value["commodityInfo"]['commodityName'];
            $new_data[$key]["ShopType"]      = '苏宁';
            $new_data[$key]["PicLogo"]       = $value['commodityInfo']['pictureUrl'][0]['picUrl'];
            $new_data[$key]["CouponMoney"]   = '';
            $new_data[$key]["Price"]         = $value['commodityInfo']['snPrice'];
            $new_data[$key]["EndPrice"]      = $value['commodityInfo']['commodityPrice'];
            $new_data[$key]["MonthSale"]     = $value['commodityInfo']['monthSales'];
            $new_data[$key]["Site"]          = "suning";
            $new_data[$key]["ItemFrom"]      = "suning";
            $new_data[$key]['Commission']    = \Common\Common::number_randtwo($value['commodityInfo']['rate']*$value['commodityInfo']['commodityPrice']/100);
            $new_data[$key]["Couponurl"]     = $value['couponInfo']['couponUrl'];
            $new_data[$key]["ShopName"]      = $value['commodityInfo']['supplierName'];
            $new_data[$key]["CouponTotal"]   = $value['couponInfo']['couponCount'];
            $new_data[$key]["CouponSurplus"] = $value['couponInfo']['couponCount'];
            $new_data[$key]["Couponurl"]          = "";
        }
        return $new_data;
    }


    /**
     * 商品详情
     */
    public function trans_detail($res){
        $arr  = [
            "GoodsId"         => $res['commodityInfo']['commodityCode'].'-'.$res['commodityInfo']['supplierCode'],
            "Title"           => $res['commodityInfo']['commodityName'],
            "ShortTitle"      => $res['commodityInfo']['commodityName'],
            "Suggest"         => $res['commodityInfo']['sellingPoint'],
            "ShopType"        => "苏宁",
            "PicLogo"         => $res['commodityInfo']['pictureUrl'][0]['picUrl'],
            "CouponMoney"     => isset($res['couponInfo']['couponValue']) && !empty($res['couponInfo']['couponValue']) ? $res['couponInfo']['couponValue'] :'0',
            "CouponSurplus"   => '',
            "Price"           => $res['commodityInfo']['snPrice'],
            "EndPrice"        => $res['commodityInfo']['commodityPrice'],
            "Commission"      => \Common\Common::number_randtwo($res['commodityInfo']['rate']*$res['commodityInfo']['commodityPrice']/100),
            "MonthSale"       => $res['commodityInfo']['monthSales'],
            "Site"            => 'suning',
            'Couponurl'       => $res['couponInfo']['couponUrl'],
            'CouponStartTime' => $res['couponInfo']['couponStartTime'] ? strtotime($res['couponInfo']['couponStartTime']) : 0,
            'CouponEndTime'   => $res['couponInfo']['couponEndTime'] ? strtotime($res['couponInfo']['couponEndTime']) : 0,
            'PicList'         => $res['commodityInfo']['pictureUrl'] ? array_column($res['commodityInfo']['pictureUrl'],'picUrl') : [],
            'SmallImages'     => $res['commodityInfo']['pictureUrl'] ? array_column($res['commodityInfo']['pictureUrl'],'picUrl') : [],
            'VideoUrl'        => '',
            "ShopName"        => $res['commodityInfo']['supplierName'],
            "ShopId"          => $res['commodityInfo']['supplierCode'],
            "ShopUrl"         => '',
            "ShopIcon"        => '',
            "DescTxt"         => sprintf("%.2f", round(4.9, 2)),
            "ServTxt"         => sprintf("%.2f", round(4.9, 2)),
            "AvgTxt"          => sprintf("%.2f", round(4.9, 2)),
        ];
        return $arr;
    }



    /**
     * 高拥商品查询列表
     */
    public function goods_list($params=[]){
        $req = new InverstmentcommodityQueryRequest();
        if(isset($params['category_id']) && !empty($params['category_id'])){
            if(!in_array($params['category_id'],[1,-1])){
                $req->setCategoryId($params['category_id']);
            }
        }
//        $req->setCityCode("025");
        $req->setCouponMark("1");
        $req->setPageIndex($params['page']);
        $req->setPicHeight("600");
        $req->setPicWidth("600");
        $req->setSize($params['page_size']);
        //api入参校验逻辑开关，当测试稳定之后建议设置为 false 或者删除该行
        $req -> setCheckParam('true');
        $serverUrl = "https://open.suning.com/api/http/sopRequest";
        $client = new DefaultSuningClient($serverUrl,$this->app_key,$this->app_secret,'json');
        $resp = $client -> execute($req);
        //$reqJson = $this->getReqJson($req);
        $resp = json_decode($resp,true);
        if(isset($resp['sn_responseContent']['sn_error'])){
            return ['status'=>false,'msg'=>$resp['sn_responseContent']['sn_error']['error_msg']];
        }else{
            $result = $resp['sn_responseContent']['sn_body']['queryInverstmentcommodity'];
            $responseResult = $this->trans_list_data($result);
            return ['status'=>true,'msg'=>'查询成功','data'=>$responseResult];
        }
    }



    /**
     * 商品详情接口
     */
    public function goods_detail($goods_id){
        $req = new CommoditydetailQueryRequest();
        //赋值……
        $req->setCityCode("025");
        $req->setCommodityStr($goods_id);
        $req->setCouponMark("1");
        $req->setPicHeight("600");
        $req->setPicWidth("600");

        $req -> setCheckParam('true');
        $serverUrl = "https://open.suning.com/api/http/sopRequest";
        $client = new DefaultSuningClient($serverUrl,$this->app_key,$this->app_secret,'json');
        $resp = $client -> execute($req);
        $resp = json_decode($resp,true);
        if(isset($resp['sn_responseContent']['sn_error'])){
            return ['status'=>false,'msg'=>$resp['sn_responseContent']['sn_error']['error_msg']];
        }else{
            $result = $resp['sn_responseContent']['sn_body']['queryCommoditydetail'];
            $result = $this->trans_detail($result[0]);
            return ['status'=>true,'msg'=>'获取成功','data'=>$result];
        }
    }



    /**
     * 分类查询
     */
    public function category_sort(){
        $req = new InverstmentcategoryidQueryRequest();
        //api入参校验逻辑开关，当测试稳定之后建议设置为 false 或者删除该行
        $req -> setCheckParam('true');
        $serverUrl = "https://open.suning.com/api/http/sopRequest";
        $client = new DefaultSuningClient($serverUrl,$this->app_key,$this->app_secret,'json');
        $resp = $client -> execute($req);
        $resp = json_decode($resp,true);
        if(isset($resp['sn_responseContent']['sn_error'])){
            return ['code'=>false,'msg'=>$resp['sn_responseContent']['sn_error']['error_msg']];
        }else{
            $result = $resp['sn_responseContent']['sn_body']['queryInverstmentcategoryid']['categoryList'];
            $result_arr=[];
            foreach($result as $key=>$value){
                $result_arr[$key]['name'] = $value['name'];
                $result_arr[$key]['category_id'] = $value['id'];
                $result_arr[$key]['site'] = 'suning';
            }
            return $result_arr;
        }
    }


    /**
     * 商品搜索筛选
     */
    public function goods_search($h_params){
        $req = new SearchcommodityQueryRequest();
        $req->setKeyword($h_params['keyword']);
        $req->setPageIndex($h_params['page']);
        $req->setPicHeight("600");
        $req->setPicWidth("600");
        $req->setSize($h_params['page_size']);
        if (isset($h_params['order_by']) && isset($h_params['sort'])){
            if ($h_params['order_by'] == 'price' && $h_params['sort'] == 'asc') {
                $req->setSortType("4");
            }
            if ($h_params['order_by'] == 'price' && $h_params['sort'] == 'desc') {
                $req->setSortType("3");
            }
            if ($h_params['order_by'] == 'sale' && $h_params['sort'] == 'desc') {
                $req->setSortType("2");
            }
            if ($h_params['order_by'] == 'sale' && $h_params['sort'] == 'asc') {
                $req->setSortType("1");
            }
            if ($h_params['order_by'] == 'commission' && $h_params['sort'] == 'desc') {
                $req->setSortType("5");
            }
        }else{
            $req->setSortType("1");
        }

//api入参校验逻辑开关，当测试稳定之后建议设置为 false 或者删除该行
        $req -> setCheckParam('true');
        $serverUrl = "https://open.suning.com/api/http/sopRequest";
        $client = new DefaultSuningClient($serverUrl,$this->app_key,$this->app_secret,'json');
        $resp = $client -> execute($req);
        $resp = json_decode($resp,true);
        if(isset($resp['sn_responseContent']['sn_error'])){
            return ['status'=>false,'msg'=>$resp['sn_responseContent']['sn_error']['error_msg']];
        }else{
            $result = $resp['sn_responseContent']['sn_body']['querySearchcommodity'];
            $result = $this->trans_list_data($result);
            return ['status'=>true,'msg'=>'查询成功','data'=>$result];
        }
    }

    /**
     * 生成推广位
     * @param $phone
     * @return bool
     */
    public function promotion_create($phone)
    {
        $req = new PromotionCreateRequest();
//赋值……
        $req->setPositionNames($phone);
        $req->setWebSiteId("1");

//api入参校验逻辑开关，当测试稳定之后建议设置为 false 或者删除该行
        $req->setCheckParam('false');
        $serverUrl = "https://open.suning.com/api/http/sopRequest";
        $client    = new DefaultSuningClient($serverUrl, $this->app_key, $this->app_secret, 'json');
        $resp      = $client->execute($req);
        $result    = json_decode($resp, true);
        if (isset($result['sn_responseContent']['sn_body']['createPromotion']['code']) && $result['sn_responseContent']['sn_body']['createPromotion']['code'] == '0000') {
            $responseMsg['pid'] = $result['sn_responseContent']['sn_body']['createPromotion']['data'][0]['promotionPositionId'];
            return ['status'=>true,'msg'=>'推广位创建成功','data'=>$responseMsg];
        } else {
            return $this->promotion_create($phone.rand(10000,10000000));
        }
    }

    public function turnHoistinglink($pid, $goods_id, $shop_id)
    {
        $req = new HoistinglinkQueryRequest();
//赋值……
        $req->setGoodsCode($goods_id);
        $req->setMertCode($shop_id);
        $req->setAdBookId($pid);

//api入参校验逻辑开关，当测试稳定之后建议设置为 false 或者删除该行
        $req->setCheckParam('false');
        $serverUrl = "https://open.suning.com/api/http/sopRequest";
        $client    = new DefaultSuningClient($serverUrl, $this->app_key, $this->app_secret, 'json');
        $resp      = $client->execute($req);
        $result    = json_decode($resp, true);
        if ($result['sn_responseContent']['sn_body']['queryHoistinglink']['status'] == 1) {
            $responReturn['url'] = $result['sn_responseContent']['sn_body']['queryHoistinglink']['deeplinkUrl'];
            $responReturn['short_url'] = $result['sn_responseContent']['sn_body']['queryHoistinglink']['shorturl'];
            $responReturn['app_url'] = $result['sn_responseContent']['sn_body']['queryHoistinglink']['deeplinkUrl'];
            return ['status' => true,'msg' => '获取成功','data' => $responReturn];
        } else {
            return ['status' => false,'msg' => '获取转链失败!'];
        }
    }


    public function storepromotionurl_query($pid, $goods_id, $shop_id)
    {
        $req = new StorepromotionurlQueryRequest();
        $req->setAdBookId($pid);
        $req->setCommCode($goods_id);
        $req->setMertCode($shop_id);
        $req->setUrlType("1");

//api入参校验逻辑开关，当测试稳定之后建议设置为 false 或者删除该行
        $req->setCheckParam('false');
        $serverUrl = "https://open.suning.com/api/http/sopRequest";
        $client    = new DefaultSuningClient($serverUrl, $this->app_key, $this->app_secret, 'json');
        $resp      = $client->execute($req);
        $result    = json_decode($resp, true);
        if (isset($result['sn_responseContent']['sn_body']['queryStorepromotionurl']['wapExtendUrl'])) {
            return urldecode($result['sn_responseContent']['sn_body']['queryStorepromotionurl']['wapExtendUrl']);
        } else {
            false;
        }
    }


    /**
     * 订单处理
     */
    private function returnOrderDeal($data){
        $responseMsgResult=[];
        foreach ($data as $k => $v) {

            $arrCount = count($v['orderDetail']);

            foreach ($v['orderDetail'] as $k1 => $v1) {
                $turnData = [
                    'orderId' => ($arrCount==1) ? $v['orderCode'] : "{$v['orderCode']}-{$v1['orderLineNumber']}",
                    'site' =>'suning',
                    'orderStatus' => $this->status[$v1['orderLineStatusDesc']],
                    'orderSrc' => 5,
                    'tag'=>'苏宁',
                    'tagItem'=>'苏宁',
                    'name' => $v1['productName'],
                    'goodsId' => $v1['goodsNum'] . '-' . $v1['sellerCode'],
                    'images' => $v1['pictureUrl'],
                    'rid' => $v1['positionId'],
                    'shopName' => $v1['sellName'],
                    'price' => $v1['payAmount'],
                    'orderType'=>in_array($this->status[$v1['orderLineStatusDesc']],[2,6]) ? 1 : 4,
                    'payMoney' => $v1['payAmount'],
                    'rebateAmount' => $v1['payAmount'] * $v1['commissionRatio'],
                    'incomeRate' => $v1['commissionRatio'],
                    'orderCreateTime' => $v1['orderSubmitTime'],
                    'orderPaidTime' => $v1['payTime'],
                    'orderEarningTime' => $v1['confirmTime'] ? $v1['confirmTime'] : null,
                    'settleTime' => $v1['confirmTime'] ? $v1['confirmTime'] : null,
                ];
                $responseMsgResult[] = $turnData;
            }
        }
        return $responseMsgResult;
    }



    /**
     * 苏宁拉单
     * https://open.suning.com/ospos/apipage/toApiMethodDetailMenuNew.do?interCode=suning.netalliance.order.query
     * @param $start_time
     * @param $end_time
     * @param int $page
     * @param int $size
     * @return array
     */
    public function getOrder($start_time,$end_time, $page = 1, $size = 50,&$responseMsgDataResult=[])
    {
//        $start_time = "2022-07-20 17:00:00";
//        $end_time = "2022-07-20 17:30:00";
        require_once 'suning/request/netalliancetx/QueryNetallianceOrderRequest.php';
        $req = new \QueryNetallianceOrderRequest();
        $req->setStartTime($start_time);   //$start_time
        $req->setEndTime($end_time);     //$end_time
        $req->setPageNo($page);
        $req->setPageSize($size);
        //api入参校验逻辑开关，当测试稳定之后建议设置为 false 或者删除该行
//        $req->setCheckParam(false);
        $serverUrl = "https://open.suning.com/api/http/sopRequest";
        $client    = new \DefaultSuningClient($serverUrl,$this->app_key, $this->app_secret, 'json');
        $resp      = $client->execute($req);
        $responseMsg    = json_decode($resp, true);
        if (isset($responseMsg['sn_responseContent']['sn_error']) && $responseMsgDataResult == []) {
            return [];
        }
        if (isset($responseMsg['sn_responseContent']['sn_body']['queryOrder']) && !empty($responseMsg['sn_responseContent']['sn_body']['queryOrder'])) {
            if ($responseMsgDataResult == []) {
                $responseMsgDataResult = $responseMsg['sn_responseContent']['sn_body']['queryOrder'];
            } else {
                $responseMsgDataResult = array_merge($responseMsgDataResult, $responseMsg['sn_responseContent']['sn_body']['queryOrder']);
            }
        }
        if (count($responseMsg['sn_responseContent']['sn_body']['queryOrder']) >= $size) {
            $this->getOrder($start_time,$end_time, $page + 1,50,$responseMsgDataResult);
        }
        return $this->returnOrderDeal($responseMsgDataResult);
    }



    public function urlQueryRequest($surlQueryRequestn_pid, $url)
    {
        $req = new CustompromotionurlQueryRequest();
        $req->setAdBookId($surlQueryRequestn_pid);
        $req->setVisitUrl($url);
        $serverUrl = "https://open.suning.com/api/http/sopRequest";
        $client = new DefaultSuningClient($serverUrl, $this->app_key, $this->app_secret, 'json');
        $resp = $client->execute($req);
        $result = json_decode($resp,true);
        if(isset($result['sn_responseContent']['sn_error'])){
            return ['status' => false,'msg' => $result['sn_responseContent']['sn_error']['error_msg']];
        }
        if ($result['sn_responseContent']['sn_body']['queryHoistinglink']['status'] == 1) {
            $responseMsgResult = [
                'url' => $result['sn_responseContent']['sn_body']['queryHoistinglink']['shorturl'],
                'short_url' => $result['sn_responseContent']['sn_body']['queryHoistinglink']['shorturl'],
                'app_path' => $result['sn_responseContent']['sn_body']['queryHoistinglink']['deeplinkUrl'],
                'page_path' => '',
                'qrcode_url' => ''
            ];
            return ['status' => true, 'msg' => "获取成功", 'data' => $responseMsgResult];
        } else {
            return ['status' => false,'msg'    => '获取转链失败!'];
        }
    }

}
